<?php

namespace app\common\controller;

use think\Controller;
use think\Request;

class Backend extends Controller
{

    // 设置属性 => 不需要登陆方法名
    protected $NoNeedLogin = ['login'];

    public function __construct()
    {
        parent::__construct();
        $NoNeedLogin = array_filter($this->NoNeedLogin);
        if (empty($NoNeedLogin)) {
            $this->isLogin();
        } else {
            $all = '*';

            $action = request()->action();

            if(!in_array($all,$NoNeedLogin) && !in_array($action,$NoNeedLogin))
            {
                $this->isLogin();
            }
        }
        $this->system();
    }

    public function isLogin()
    {
        $LoginAdmin = !empty(cookie('LoginAdmin')) ? cookie('LoginAdmin') : '';
        if ($LoginAdmin) {
            $adminList = model('Admin')->select();
            $adminid = 0;
            foreach ($adminList as $item) {
                $val = md5($item['id'] . $item['salt']);
                if ($LoginAdmin == $val) {
                    $adminid = $item['id'];
                    break;
                }
            }
            $admin = model('Admin')->find($adminid);
            if (!$admin) {
                cookie('LoginAdmin', null);
                $this->error('非法登录', url('admin/index/login', null, 2));
            }
            if ($admin['state'] == 0) {
                cookie('LoginAdmin', null);
                $this->error('该账号被禁用，请联系管理员', null, null, 1.5);
            }

            // 给所有继承Backend的控制器 赋值一个登陆信息
            $this->LoginAdmin = $admin;

            // 赋值给所有视图
            $this->assign([
                'LoginAdmin' => $admin
            ]);
        } else {
            $this->error('请先登陆', url("admin/index/login"));
        }
    }

    public function System() {
        [
            'id' => 1,
            'title' => 'Logo',
            'key' => 'Logo',
            'value' => 111,
            'type' => 'text'
        ];
        $SystemData = [];
        $ConfigList = model('Config')->select();

        foreach($ConfigList as $item)
        {
            $SystemData[$item['key']] = $item['value'];
        }
        // halt($SystemData);
        $this->assign([
            'system' => $SystemData
        ]);
    }
}
